package net.hserver.sync.controller.system.log;

import cn.hserver.plugin.web.annotation.WebSocket;
import cn.hserver.plugin.web.context.WebConstConfig;
import cn.hserver.plugin.web.handlers.Ws;
import cn.hserver.plugin.web.interfaces.WebSocketHandler;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@WebSocket("/log")
public class LogWebSocket implements WebSocketHandler {

    private final static Map<String, Ws> WS = new ConcurrentHashMap<>();

    @Override
   public void onConnect(Ws ws) {
        log.info("websocket连接成功:{}",ws.getUid());
        if (!WS.containsKey(ws.getUid())) {
            WS.put(ws.getUid(), ws);
        }
    }

    @Override
    public void onMessage(Ws ws) {

    }

    @Override
    public void disConnect(Ws ws) {
        log.info("websocket断开连接:{}",ws.getUid());
        WS.remove(ws.getUid());
    }

    public static void sendMessage(Object message) {
        for (Ws value : WS.values()) {
            try {
                String s = WebConstConfig.JSON.writeValueAsString(message);
                value.send(s).addListener(future -> {
                    log.debug("websocket发送消息:{}", future.isSuccess());
                });
            }catch (Exception e){
                log.error("websocket发送消息失败:{}", e.getMessage());
            }
        }
    }

}
